import { Injectable, Inject, BadRequestException } from '@nestjs/common';
import {
  CreateEmployeeDto,
  UpdateEmployeeDto,
  Employee,
  EmployeeModelReturnType
} from 'libs/db/src/schemas';

@Injectable()
export class EmployeeService {
  constructor(
    @Inject(Employee.name)
    private readonly employeeModel: EmployeeModelReturnType
  ) {}
  async create(createEmployeeDto: CreateEmployeeDto) {
    const { name } = createEmployeeDto;
    const emp = await this.employeeModel.findOne({ name }).exec();
    console.log(emp);

    if (!!emp) {
      throw new BadRequestException('姓名已存在,请勿重复添加!');
    }
    return this.employeeModel.create(createEmployeeDto);
  }

  findAll() {
    return this.employeeModel.find().select('-__v').exec();
  }

  findOne(id: string) {
    return this.employeeModel.findById(id).select('-__v').exec();
  }

  update(id: string, updateEmployeeDto: UpdateEmployeeDto) {
    return this.employeeModel.findByIdAndUpdate(id, updateEmployeeDto).exec();
  }

  remove(id: string) {
    return this.employeeModel.findByIdAndDelete(id).exec();
  }
}
